<!--
 * @Author: your name
 * @Date: 2021-12-06 19:38:26
 * @LastEditTime: 2022-03-06 11:33:48
 * @LastEditors: your name
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \soldier\src\components\Upload\upload.vue
-->
<template>
  <div>
    <el-form label-width="120px" class="dialog-form" label-position="right">
      <el-form-item label="上传文件">
        <el-upload
          ref="upload"
          drag
          accept=".jpg, .jpeg, .bmp, .png, .gif"
          name="file"
          :auto-upload="false"
          :limit="1"
          :headers="headers"
          :action="apiUrl"
          :before-upload="beforeUpload"
          :on-success="uploadSuccess"
          :on-error="uploadError"
        >
          <i class="el-icon-upload" />
          <div class="el-upload__text">
            将文件拖到此处，或
            <em>点击上传</em>
          </div>
          <div slot="tip" class="el-upload__tip">
            只能上传excel/wps格式的文件，且不超过200M
          </div>
        </el-upload>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="doUpload">确定</el-button>
    </div>
  </div>
</template>

<script>
  export default {
    props: {
      apiUrl: '',
      rowid: '',
    },
    data() {
      return {
        headers: {
          token: localStorage.getItem('token') || '',
          'content-Type': 'multipart/form-data',
        },
      }
    },
    methods: {
      beforeUpload(file) {
        console.log(file)
        if (!this.$util.validFile(file)) {
          this.$message({
            message: '上传文件格式不正确!',
            type: 'error',
          })
          return false
        }
        if (file.size / 1024 / 1024 > 200) {
          this.$message({
            message: '上传文件大小不能超过200MB!',
            type: 'error',
          })
          return false
        }
        return true
      },
      uploadSuccess(res) {
        if (res.status == 200) {
          this.$message({
            message: '导入成功',
            type: 'success',
          })
          this.$emit('success')
        } else {
          this.$message({
            message: res.message,
            type: 'error',
          })
        }
      },
      uploadError(e) {
        this.$message({
          message: '上传失败，请按照指定的模板格式进行上传',
          type: 'error',
        })
      },
      doUpload() {
        this.$refs.upload.submit()
      },
    },
  }
</script>

<style></style>
